package com.wn.framework.ext

import android.os.SystemClock
import android.view.View
import com.wn.framework.R

/**
 * @Author: wn
 * @Date: 2024/8/28 15:41
 * @Description: View扩展
 * 1 节流 2 防抖
 */
/**
 * 节流 ,连续点击 大于设定时间段才会触发
 */
inline fun View.onClick(wait: Long = 200, crossinline block: (View) -> Unit) {
  setOnClickListener(throttleClick(wait, block))
}

inline fun throttleClick(
  wait: Long = 200,
  crossinline block: (View) -> Unit,
): View.OnClickListener =
  View.OnClickListener { v ->
    val current = SystemClock.uptimeMillis()
    val lastClickTime = (v.getTag(R.id.click_time_stamp) as? Long) ?: 0
    if (current - lastClickTime > wait) {
      v.setTag(R.id.click_time_stamp, current)
      block(v)
    }
  }

/**
 * 防抖 最后一次点击与上一次点击 ，时间间隔大于指定 才会触发
 */
fun View.onDebounceClick(wait: Long = 200, block: (View) -> Unit) {
  setOnClickListener(debounceClick(wait, block))
}

private fun debounceClick(wait: Long = 200, block: (View) -> Unit): View.OnClickListener {
  return View.OnClickListener { v ->
    var action = (v.getTag(R.id.click_debounce_action) as? DebounceAction)
    if (action == null) {
      action = DebounceAction(v, block)
      v.setTag(R.id.click_debounce_action, action)
    } else {
      action.block = block
    }
    v.removeCallbacks(action)
    v.postDelayed(action, wait)
  }
}

class DebounceAction(val view: View, var block: (View) -> Unit) : Runnable {
  override fun run() {
    if (view.isAttachedToWindow) {
      block(view)
    }
  }
}